package cn.yll.gateway.config;

import cn.yll.common.constant.MyConstants;
import cn.yll.common.exception.BsException;
import cn.yll.common.utils.JwtTokenUtil;
import cn.yll.common.utils.RedisUtil;
import cn.yll.gateway.config.properties.IgnoreWhiteProperties;
import cn.yll.gateway.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * 网关鉴权
 * 
 * @author ruoyi
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered
{
    private static final Logger log = LoggerFactory.getLogger(AuthFilter.class);

    // 排除过滤的 uri 地址，nacos自行添加
    @Autowired
    private IgnoreWhiteProperties ignoreWhite;

    @Autowired
    private RedisUtil redisUtil;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();

        String url = request.getURI().getPath();
        // 跳过不需要验证的路径
        if (StringUtils.matches(url, ignoreWhite.getWhites())) {
            return chain.filter(exchange);
        }
        String token = getToken(request);
        if (StringUtils.isEmpty(token)) {
            return unauthorizedResponse(exchange, "令牌不能为空", null);
        }
        try {
            Long userId = JwtTokenUtil.getUserIdByJwtToken(token);
            // 设置用户信息到请求
            addHeader(mutate, MyConstants.LOGIN_USER_ID, userId);
        } catch (BsException e) {
            return unauthorizedResponse(exchange, e.getMessage(), e.getBsErrEnum().getCode());
        }
        // 内部请求来源参数清除
        removeHeader(mutate, MyConstants.FROM_SOURCE);
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }

    private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value) {
        if (value == null) {
            return;
        }
        String valueStr = value.toString();
        String valueEncode = ServletUtils.urlEncode(valueStr);
        mutate.header(name, valueEncode);
    }

    private void removeHeader(ServerHttpRequest.Builder mutate, String name) {
        mutate.headers(httpHeaders -> httpHeaders.remove(name)).build();
    }

    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg, Integer code) {
        log.error("[鉴权异常处理]请求路径:{}, msg:{}", exchange.getRequest().getPath(), msg);
        Integer status = Objects.isNull(code) ? HttpStatus.UNAUTHORIZED : code;
        return ServletUtils.webFluxResponseWriter(exchange.getResponse(), msg, status);
    }

    /**
     * 获取请求token
     */
    private String getToken(ServerHttpRequest request) {
        return request.getHeaders().getFirst(MyConstants.TOKEN_KEY);
    }

    @Override
    public int getOrder()
    {
        return -200;
    }
}